<template>
	<a-directory-tree
	  :load-data 			='onLoadData'
	  :tree-data 			='ajax.data'
	  v-model:expandedKeys 	='expandedKeys'
	  v-model:selectedKeys 	='selectedKeys'
	  :replaceFields = '{ key:idStr, title:nameStr }'
	  show-icon
	>
		<template #custom='{ selected }'>
		    <FolderOpenOutlined v-if='selected' />
		    <FolderOutlined v-else />
		</template>
	</a-directory-tree>
</template>

<script>
	import { ref, watch, defineComponent } from 'vue'
	import { FolderOutlined, FolderOpenOutlined } from '@ant-design/icons-vue'
	import { Tree } from 'ant-design-vue'
	app.use(Tree)
	
	/* --------------------------- Page --------------------------- */
	export default defineComponent({
		components: { FolderOutlined, FolderOpenOutlined },
		props:{
			idStr 		: { type: String, default: 'fileId' },
			nameStr 	: { type: String, default: 'fileName' },
			fileType 	: { type: Number, default: 1 },
			rootApi 	: { type: String, default: 'file/manage/rootDirs' },
			childApi 	: { type: String, default: 'file/manage/childDirs' }
		},
		emits:{ load: null},
		setup({ rootApi, childApi, fileType }, ctx) {
			const expandedKeys = ref([])
			const selectedKeys = ref([])
			const ajax = ref({ data:[] })
			const myAjax = ref({ loading:false })
			let currentNode = null
			
			const refreshRoot = ()=>{
				$http.pull(myAjax, rootApi, { id: fileType, loading:true, onLoading: v => ctx.emit('load', v) }).then(data=>{
					ajax.value.data = data.map(v => ({ ...v, slots: { icon: 'custom' }}))
				})
			}
			
			refreshRoot()
			
			const refresh = pid => $http.pull(myAjax, childApi, { id:fileType, param: { parentId:pid }, onLoading: v => ctx.emit('load', v)  }).then(data => {
				currentNode.children = data.map(v => ({ ...v, slots: { icon: 'custom' }}))
			})
			
			const refreshOnLy = pid => $http.pull(myAjax, childApi, { id:fileType, param: { parentId:pid }, onLoading: v => ctx.emit('load', v)  }).then(data => {
				if($fn.hasArray(data)){
					currentNode.children = data.map(v => ({ ...v, slots: { icon: 'custom' }}))
				}
			})
			
			return {
				ajax,
				expandedKeys,
				selectedKeys,
				onLoadData: node => {
					return new Promise(resolve => {
						if (node.dataRef.children) {
							resolve()
							return
						}
						
						$http.pull(myAjax, childApi, { id:fileType, param: { parentId: node.dataRef.fileId }, onLoading: v => ctx.emit('load', v)  }).then(data => {
							node.dataRef.children = data.map(v => ({ ...v, slots: { icon: 'custom' }}))
							
							if($fn.hasArray(node.dataRef.children)){
								currentNode = node.dataRef
							}
							
							resolve()
						})
					})
				},
				refresh,
				refreshOnLy,
				refreshRoot
			}
		}
	})
</script>